package cn.zf233.jwtshiro.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {

    private static final int TIMEOUT_SECOND = 60 * 60 * 24;

    private static final String TOKEN = "token!Q@W3e4r";

    public static String getToken(Map<String, Object> loadMap) {
        JWTCreator.Builder builder = JWT.create();
        loadMap.forEach((k, v) -> builder.withClaim(k, String.valueOf(v)));
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, TIMEOUT_SECOND);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN));
    }

    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);  // 如果验证通过，则不会把报错，否则会报错
    }

    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
